package com.windowes.weichang.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.windowes.weichang.access.UserContext;
import com.windowes.weichang.common.ServerResponse;
import com.windowes.weichang.dao.*;
import com.windowes.weichang.dto.ShopDto;
import com.windowes.weichang.dto.WalletTDO;
import com.windowes.weichang.dto.WidthdrawApplyDTO;
import com.windowes.weichang.model.BDShop;
import com.windowes.weichang.pojo.*;
import com.windowes.weichang.utils.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/***
 *
 * @author: yangqing
 * @email: qing.yang@bangdao-tech.com
 * @createTime: 2018/5/28 上午7:43
 * @description:
 *
 **/
@Service
public class ShopService {

    public static final String SHOP_KEY = "sid";
    private static List arrayList = null;

    static {
        arrayList = new CopyOnWriteArrayList();
        arrayList.add("F");
        arrayList.add("P");
        arrayList.add("S");
    }

    @Autowired
    WShopMapper shopMapper;

    @Autowired
    DistrictService districtService;

    @Autowired
    WShopBannerMapper shopBannerMapper;

    @Autowired
    ShopApplyMapper shopApplyMapper;


    @Autowired
    WUserMapper userMapper;

    @Autowired
    AMapService aMapService;

    @Autowired
    DemandMapper demandMapper;

    @Autowired
    DemandCommentMapper commentMapper;
    @Autowired
    UserCoreService userCoreService;
    @Autowired
    DemandCancleLogMapper demandCancleLogMapper;
    @Autowired
    DemandShopApplyMapper demandShopApplyMapper;
    @Autowired
    DemandShopApplyDtlMapper dtlMapper;
    @Autowired
    DemandShopPayFlowMapper demandShopPayFlowMapper;


    public ServerResponse list(String keyword, int pageNo, int pageSize) {
        Page<WShop> page = new Page<>(pageNo, pageSize);
        page.setRecords(shopMapper.selectByPage(page, keyword, "T"));
        return ServerResponse.createBySuccess(page);
    }


    /**
     * 添加店铺
     *
     * @param shopDto
     * @return
     */
    @Transactional
    public ServerResponse add(ShopDto shopDto) {
        if (shopDto == null || shopDto.getShop() == null) {
            return ServerResponse.createBySuccessMessage("请提交店铺信息!");
        }
        WShop shop = shopDto.getShop();
        shop.setApplyState("T");
        try {
            if (shop.getId() == null) {
                if (StringUtils.isBlank(shop.getPhone())) {
                    return ServerResponse.createByErrorMessage("请设置店主!");
                }

                //判断当前人员是否存在
                Integer userId = getUserId(shop);
                shop.setUserId(userId);
                if (shop.getProvinceId() != null && shop.getCityId() != null && shop.getAreaId() != null && shop.getStreetId() != null) {
                    ServerResponse<String> standardAddress = districtService.getStandardAddress(shop.getProvinceId(), shop.getCityId(), shop.getAreaId(), shop.getStreetId());
                    String data = standardAddress.getData();
                    shop.setStandAddress(data);
                }

                shopMapper.insertSelective(shop);
                String generateNo = generateNo(shop.getId());
                shop.setShopNo(generateNo);
                shopMapper.updateByPrimaryKeySelective(shop);
                if (shopDto.getShopBanners() != null && !shopDto.getShopBanners().isEmpty()) {
                    for (WShopBanner banner : shopDto.getShopBanners()) {
                        banner.setShopId(shop.getId());
                        shopBannerMapper.insertSelective(banner);
                    }
                }
            } else {
                if (StringUtils.isBlank(shop.getPhone())) {
                    return ServerResponse.createByErrorMessage("请设置店主!");
                }

                //判断当前人员是否存在
                Integer userId = getUserId(shop);

                shop.setUserId(userId);
                shopMapper.updateByPrimaryKeySelective(shop);
            }
            //开始同步地理位置操作
            if (StringUtils.isEmpty(shop.getGeoId())) {
                ServerResponse serverResponse = aMapService.dsJob(shop.getName(), shop.getDtlAddress(), shop.getLongtitude(), shop.getLatitude(), shop.getShopkeeper(), shop.getId());
                shop.setGeoId((String) serverResponse.getData());
                shopMapper.updateByPrimaryKeySelective(shop);
            } else {
                aMapService.updateItem(shop.getGeoId(), shop.getName(), shop.getDtlAddress(), shop.getLongtitude(), shop.getLatitude(), shop.getShopkeeper(), shop.getId());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createBySuccessMessage("操作成功");
    }

    private Integer getUserId(WShop shop) {
        Integer userId = null;
        ServerResponse<WUser> userByPhone = userCoreService.getUserByPhone(shop.getPhone());
        if (!userByPhone.isSuccess()) {
            //插入人员
            WUser wUser = new WUser();
            wUser.setName(shop.getShopkeeper());
            wUser.setPhone(shop.getPhone());
            wUser.setPassword("123456");
            wUser.setFrom((short) 1);
            userMapper.insertSelective(wUser);
            userId = wUser.getId();
        } else {
            userId = userByPhone.getData().getId();
        }
        return userId;
    }

    /**
     * 添加店铺
     *
     * @param shopId
     * @return
     */
    public ServerResponse delete(Integer shopId) {
        if (shopId == null) {
            return ServerResponse.createByErrorMessage("shopId不能为空!");
        }
        try {
            shopMapper.deleteByPrimaryKey(shopId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createBySuccessMessage("添加成功");
    }

    public String generateNo(Integer id) {
        return String.format("WS%07d", id);
    }

    /**
     * 数据同步
     *
     * @return
     */
    public ServerResponse dataSynchronized() {
        ServerResponse list = list(null, 1, 65535);
        if (list.isSuccess()) {
            Page<WShop> page = (Page<WShop>) list.getData();
            List<WShop> records = page.getRecords();
            for (int i = 0; records != null && i < records.size(); i++) {
                WShop shop = records.get(i);
                aMapService.dsJob(shop.getName(), shop.getDtlAddress(), shop.getLongtitude(), shop.getLatitude(), shop.getShopkeeper(), shop.getId());
                // TODO: 2018/8/5 更新店铺位置
            }

            return ServerResponse.createBySuccessMessage("店铺数据同步完成");
        } else {
            return ServerResponse.createByErrorMessage("没有店铺信息!");
        }
    }

    public ServerResponse search(BigDecimal longtitude, BigDecimal latitude, String q, long radius) {
        //默认查询全部
        if (longtitude == null && latitude == null && StringUtils.isEmpty(q)) {
            List<WShop> shopList = shopMapper.selectAll();
            return ServerResponse.createBySuccess("已为您自动匹配到店铺", shopList);
        }
        String location = longtitude + "," + latitude;
        ServerResponse<List<BDShop>> search = aMapService.search(location, radius + "", "", q);
        if (search.isSuccess()) {
            List<BDShop> bdShops = search.getData();
            List<WShop> shopList = new ArrayList<>();
            for (BDShop bdShop : bdShops) {
                WShop shop = shopMapper.selectByPrimaryKey(bdShop.getShopId());
                shop.setDistance(bdShop.getDistance());
                shopList.add(shop);
            }
            return ServerResponse.createBySuccess("已为您自动匹配到店铺", shopList);
        }
        return search;
    }

    public ServerResponse item(Integer id) {
        if (id == null) {
            return ServerResponse.createByErrorMessage("请提交店铺ID!");
        }
        WShop shop = shopMapper.selectByPrimaryKey(id);
        if (shop == null) {
            return ServerResponse.createByErrorMessage("店铺不存在,请核实!");
        }

        List<Integer> shopIds = new ArrayList<>();
        shopIds.add(shop.getId());
        List<Demand> demands = demandMapper.selectAllByShopIds(shopIds);
        //开始计算订单量
        int size = demands.size();
        shop.setOrderNum(size);
        BigDecimal totalMoney = demands.stream().map(Demand::getTotalPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        //计算总交易额
        shop.setTotalPrice(totalMoney);
        //订单均单价
        shop.setAverageOrderPrice(new BigDecimal(0.0));
        if (size > 0) {
            shop.setAverageOrderPrice(shop.getTotalPrice().divide(new BigDecimal(size), RoundingMode.HALF_UP));
        }

        //计算接单率

        List<DemandCancleLog> cancleLogs = demandCancleLogMapper.selectByShopId(shop.getId());
        shop.setAcceptRate(0);
        if (!demands.isEmpty()) {
            int acceptRate = (demands.size() - cancleLogs.size()) * 100 / demands.size();
            shop.setAcceptRate(acceptRate);
        }
        List<DemandComment> comments = commentMapper.selectByShopId(shop.getId());

        //计算评论数
        int commentNum = comments.size();
        shop.setCommentNum(commentNum);

        Integer comprehensiveStar = 0;
        Integer serviceStar = 0;
        Integer installStar = 0;
        Integer qualityStar = 0;
        Integer handleStar = 0;


        for (DemandComment comment : comments) {
            comprehensiveStar += comment.getComprehensiveStar();
            serviceStar += comment.getServiceStar();
            installStar += comment.getInstallStar();
            qualityStar += comment.getQualityStar();
            handleStar += comment.getHandleStar();
        }


        shop.setComprehensiveStar(0);
        shop.setServiceStar(0);
        shop.setInstallStar(0);
        shop.setQualityStar(0);
        shop.setHandleStar(0);

        //综合评价
        if (commentNum != 0) {
            int comprehensiveStar1 = comprehensiveStar * 100 / (5 * commentNum);
            int cstar = calc(comprehensiveStar1);
            shop.setComprehensiveStar(cstar);
        }
        //服务态度
        if (commentNum != 0) {
            shop.setServiceStar(calc(serviceStar * 100 / (5 * commentNum)));
        }
        //安装及时
        if (commentNum != 0) {
            shop.setInstallStar(calc(installStar * 100 / (5 * commentNum)));
        }
        //商品质量
        if (commentNum != 0) {
            shop.setQualityStar(calc(qualityStar * 100 / (5 * commentNum)));
        }
        //施工质量
        if (commentNum != 0) {
            shop.setHandleStar(calc(handleStar * 100 / (5 * commentNum)));
        }

        return ServerResponse.createBySuccess("获取成功!", shop);
    }

    private int calc(int comprehensiveStar1) {
        return (int) (comprehensiveStar1 * 0.01 * 5);
    }

    /**
     * 申请店铺
     *
     * @param applyInfoDto
     * @return
     */
    @Transactional
    public ServerResponse apply(WShop applyInfoDto) {
        if (applyInfoDto == null) {
            return ServerResponse.createByErrorMessage("请提交认证信息!");
        }

        if (StringUtils.isEmpty(applyInfoDto.getName())) {
            return ServerResponse.createByErrorMessage("请提交店名!");
        }

        WUser user = UserContext.getUser();
        //校验是否存在在途工单
        ShopApply shopApply = shopApplyMapper.selectByApplyState(user.getId(), null, "P");
        if (shopApply != null) {
            return ServerResponse.createByErrorMessage("已存在在途工单,请耐心等待!");
        }

        if (applyInfoDto.getId() == null) {
            applyInfoDto.setUserId(user.getId());
            applyInfoDto.setApplyState("P");
            shopMapper.insertSelective(applyInfoDto);
            String generateNo = generateNo(applyInfoDto.getId());
            applyInfoDto.setShopNo(generateNo);
            shopMapper.updateByPrimaryKeySelective(applyInfoDto);

            shopApply = new ShopApply();
            shopApply.setApplyState("P");
            shopApply.setUserId(user.getId());
            shopApply.setShopId(applyInfoDto.getId());
            shopApplyMapper.insertSelective(shopApply);
        } else {
            WShop shop = shopMapper.selectByPrimaryKey(applyInfoDto.getId());
            if (shop == null) {
                return ServerResponse.createByErrorMessage("店铺已经被删除,请核实!");
            }
            if (StringUtils.equals("P", shop.getApplyState())) {
                return ServerResponse.createByErrorMessage("请等待审核结束,再修改认证信息!");
            }
            applyInfoDto.setApplyState(null);
            applyInfoDto.setCreateTime(null);
            shopMapper.updateByPrimaryKeySelective(applyInfoDto);

            shopApply = new ShopApply();
            shopApply.setApplyState("P");
            shopApply.setUserId(user.getId());
            shopApply.setShopId(applyInfoDto.getId());
            shopApplyMapper.insertSelective(shopApply);
        }
        //更新店铺人员姓名
        String shopkeeper = applyInfoDto.getShopkeeper();
        WUser keeper = new WUser();
        keeper.setId(shopApply.getUserId());
        keeper.setName(shopkeeper);
        userMapper.updateByPrimaryKeySelective(user);

        return ServerResponse.createBySuccessMessage("提交成功,请耐心等待1-2个工作日！");
    }

    /**
     * 获取等待审核列表
     *
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     */
    public ServerResponse waittingList(String keyword, int pageNo, int pageSize, String applyState) {
        if (!arrayList.contains(applyState)) {
            return ServerResponse.createByErrorMessage("状态不正确,请核实!");
        }

        Page<WShop> page = new Page<>(pageNo, pageSize);
        page.setRecords(shopMapper.selectByPage(page, keyword, applyState));
        return ServerResponse.createBySuccess(page);
    }


    /**
     * 允许店铺通过申请
     *
     * @param id
     * @return
     */
    @Transactional
    public ServerResponse approve(Integer id) {
        if (id == null) {
            return ServerResponse.createByErrorMessage("请提交店铺ID!");
        }
        //更新店铺状态
        WShop shop = shopMapper.selectByPrimaryKey(id);
        if (shop == null) {
            return ServerResponse.createByErrorMessage("店铺不存在,请核实!");
        }
        //更新店铺状态
        shop.setApplyState("T");
        shopMapper.updateByPrimaryKeySelective(shop);
        //更新申请记录状态
        ShopApply shopApply = shopApplyMapper.selectByApplyState(null, shop.getId(), "P");
        if (shopApply == null) {
            return ServerResponse.createByErrorMessage("状态异常,请联系管理员!");
        }
        shopApply.setApplyState("T");
        WUser user = UserContext.getUser();
        shopApply.setOperateUid(user.getId());
        shopApplyMapper.updateByPrimaryKeySelective(shopApply);
        return ServerResponse.createBySuccessMessage("操作成功!");
    }

    /**
     * 拒绝店铺通过申请
     *
     * @param id
     * @return
     */
    @Transactional
    public ServerResponse refuse(Integer id, String reason) {
        if (id == null) {
            return ServerResponse.createByErrorMessage("请提交店铺ID!");
        }

        if (StringUtils.isEmpty(reason)) {
            return ServerResponse.createByErrorMessage("请提交不通过原因!");
        }
        //更新店铺状态
        WShop shop = shopMapper.selectByPrimaryKey(id);
        if (shop == null) {
            return ServerResponse.createByErrorMessage("店铺不存在,请核实!");
        }

        //更新申请记录状态
        ShopApply shopApply = shopApplyMapper.selectByApplyState(null, shop.getId(), "P");
        if (shopApply == null) {
            return ServerResponse.createByErrorMessage("状态异常,请联系管理员!");
        }
        shopApply.setApplyState("F");
        shopApply.setReason(reason);
        WUser user = UserContext.getUser();
        shopApply.setOperateUid(user.getId());
        shopApplyMapper.updateByPrimaryKeySelective(shopApply);

        shop.setApplyState("F");
        shopMapper.updateByPrimaryKeySelective(shop);
        return ServerResponse.createBySuccessMessage("操作成功!");
    }


    /**
     * 钱包
     *
     * @return
     */
    public ServerResponse wallet() {
        WalletTDO wallet = new WalletTDO();
        Integer sId = UserContext.getUser().getSId();
        BigDecimal amount = demandMapper.sumByShopId(sId, 11);
        wallet.setAmount(new BigDecimal(0));
        if (amount != null) {
            wallet.setAmount(amount);
        }
        return ServerResponse.createBySuccess(wallet);
    }

    public ServerResponse withdrawList(int pageNo, int pageSize) {
        Page<DemandShopApply> page = new Page<>(pageNo, pageSize);
        Integer sId = UserContext.getUser().getSId();
        Integer deptId = UserContext.getDeptId();
        page.setRecords(demandShopApplyMapper.selectWithdraw(page, deptId, sId));
        return ServerResponse.createBySuccess(page);
    }

    public ServerResponse withdrawApplyList(int pageNo, int pageSize) {
        Page<DemandShopApply> page = new Page<>(pageNo, pageSize);
        Integer deptId = UserContext.getDeptId();
        page.setRecords(demandShopApplyMapper.selectWithdraw(page, deptId, null));
        return ServerResponse.createBySuccess(page);
    }

    @Transactional
    public ServerResponse submitWithdraw(WidthdrawApplyDTO widthdrawApplyDTO) {
        if (widthdrawApplyDTO == null) {
            return ServerResponse.createByErrorMessage("参数错误!");
        }

        //检查当前是否存在可申请金额
        Integer sId = UserContext.getUser().getSId();
        BigDecimal amount = demandMapper.sumByShopId(sId, 11);
        if (amount == null || amount.compareTo(new BigDecimal(0.0)) == 0) {
            return ServerResponse.createByErrorMessage("暂无可提款项!");
        }

        List<Demand> demands = demandMapper.selectCalcByShopId(sId, 11);
        if (demands.isEmpty()) {
            return ServerResponse.createByErrorMessage("暂无可提款项1!");
        }

        DemandShopApply record = new DemandShopApply();
        record.setAcctNo(widthdrawApplyDTO.getAcctNo());
        record.setAmount(amount);
        record.setDemandCnt(demands.size());
        record.setRemark("客户申请提现");
        record.setShopId(sId);
        record.setStatus(0);
        Integer deptId = demands.get(0).getDeptId();
        record.setDeptId(deptId);
        Integer userId = UserContext.getUser().getId();
        record.setUserId(userId);
        String applyBatchNo = UUIDUtil.getApplyBatchNo();
        record.setBatchNo(applyBatchNo);
        demandShopApplyMapper.insertSelective(record);

        DemandShopApplyDtl rd = null;
        List<DemandShopApplyDtl> dtls = Lists.newArrayList();
        List<Integer> demandIds = new ArrayList<>();
        for (Demand item : demands) {
            rd = new DemandShopApplyDtl();
            rd.setDemandId(item.getId());
            rd.setUserId(userId);
            rd.setDeptId(deptId);
            rd.setBatchNo(applyBatchNo);
            rd.setApplyId(record.getId());
            rd.setPayWay(widthdrawApplyDTO.getPayWay());
            rd.setMoney(item.getWaittingPayForShop());
            dtls.add(rd);
            demandIds.add(item.getId());
        }
        dtlMapper.insertAll(dtls);
        demandMapper.batchUpdateShopCalacStatus(1, demandIds);


        return ServerResponse.createBySuccessMessage("操作成功!");
    }


    @Transactional
    public ServerResponse approveWithdraw(Integer applyId) {
        if (applyId == null) {
            return ServerResponse.createByErrorMessage("参数错误!");
        }

        DemandShopApply record = demandShopApplyMapper.selectByPrimaryKey(applyId);
        record.setId(applyId);
        record.setStatus(1);
        demandShopApplyMapper.updateByPrimaryKeySelective(record);
        //插入打款记录
        List<DemandShopApplyDtl> demandShopApplyDtls = dtlMapper.selectByApplyId(applyId);
        List<DemandShopPayFlow> shopPayFlows = Lists.newArrayList();
        List<Integer> demandIds = new ArrayList<>();
        for (DemandShopApplyDtl dtl : demandShopApplyDtls) {
            DemandShopPayFlow shopPayFlow = new DemandShopPayFlow();
            shopPayFlow.setTitle("放款");
            shopPayFlow.setShopId(dtl.getShopId());
            shopPayFlow.setDemandId(dtl.getDemandId());
            shopPayFlow.setAccount(record.getAcctNo());
            shopPayFlow.setMoney(dtl.getMoney());
            shopPayFlow.setPayStep(0);
            shopPayFlow.setOperateType("P");
            shopPayFlow.setPayWay(dtl.getPayWay());
            shopPayFlow.setRemark(record.getRemark());
            shopPayFlows.add(shopPayFlow);
            demandIds.add(dtl.getDemandId());
        }

        demandShopPayFlowMapper.insertAll(shopPayFlows);
        // 批量更新订单商家打款状态
        demandMapper.batchUpdateShopCalacStatus(2, demandIds);
        return ServerResponse.createBySuccessMessage("操作成功!");
    }


}
